/***************************************************************************************
 The copyright in this software is being made available under the BSD License, included
 below. This software may be subject to other third party rights,including patent rights,
 and no such rights are granted under this license.

 Regents of the Tsinghua University, Peking University, Zhejiang University, HKUST
 Tsinghua University, Peking University, Zhejiang University, HKUST 2011

 Copyright (c) 2011, Regents of the Tsinghua University, Peking University, Zhejiang
 University, HKUST. All Rights Reserved.

 Redistribution and use in source and binary forms, with or without modification, are
 permitted provided that the following conditions are met:
   * Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
   * Neither the names of the copyright holders nor the names of its
     contributors may be used to endorse or promote products derived from this
     software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 OF SUCH DAMAGE.
***************************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>

#include "contributors.h"
#include "global.h"
#include "vlc.h"
#include "bbv.h"
#include "macroblock.h"

static copyright_t CopyRights, *cp = &CopyRights;
static camera_para_t CameraParameter, *camera = &CameraParameter;
static output_stream_t ORABS, *pORABS = &ORABS;

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static void open_output_stream( output_stream_t * p, char *fname )
{
    p->f = fopen( fname, "wb" );
    if ( p->f == NULL )
    {
        printf( "\nCan't open file %s", fname );
        exit( -1 );
    }

    p->uPreBytes       = 0xffffffff;
    p->iBytePosition   = 0;
    p->iBitOffset      = 0;
    p->iNumOfStuffBits = 0;
    p->iBitsCount      = 0;
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static void close_output_stream( output_stream_t * p )
{
    if ( p->iBitOffset )
        fwrite( p->buf, 1, p->iBytePosition + 1, p->f );
    else
        fwrite( p->buf, 1, p->iBytePosition, p->f );
    fclose( p->f );
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static int write_1_bit( output_stream_t * p, int b )
{
    static const byte bit[8] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
    int i;

    if ( p->iBytePosition == STREAM_BUF_SIZE )
    {
        i = fwrite( p->buf, 1, STREAM_BUF_SIZE, p->f );
        if ( i != STREAM_BUF_SIZE )
        {
            printf( "Fatal: write file error, exit (-1)\n" );
            exit( -1 );
        }
        p->iBytePosition = 0;
        p->iBitOffset = 0;
    }
    p->uPreBytes <<= 1;
    if ( b )
    {
        p->buf[p->iBytePosition] |= bit[p->iBitOffset];
        p->uPreBytes |= 1;
    }
    else
    {
        p->buf[p->iBytePosition] &= ( ~bit[p->iBitOffset] );
    }
    p->iBitOffset++;
    if ( p->iBitOffset == 8 )
    {
        p->iBitOffset = 0;
        p->iBytePosition++;
    }
    p->iBitsCount++;
    return 0;
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static int write_n_bit( output_stream_t * p, int b, int n )
{
    if ( n > 30 )
        return 1;
    while ( n > 0 )
    {
        write_1_bit( p, b & ( 0x01 << ( n - 1 ) ) );
        n--;
    }
    return 0;
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static int write_align_stuff( output_stream_t * p )
{
    unsigned char c;

    c = 0xff << ( 8 - p->iBitOffset );
    p->buf[p->iBytePosition] = ( c & p->buf[p->iBytePosition] ) | ( 0x80 >> ( p->iBitOffset ) );
    p->iBitsCount           += 8 - p->iBitOffset;
    p->uPreBytes             = ( p->uPreBytes << ( 8 - p->iBitOffset ) ) & c;
    p->iNumOfStuffBits      += 8 - p->iBitOffset;
    p->iBitOffset            = 0;
    p->iBytePosition++;
    return 0;
}


/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static int write_start_code( output_stream_t * p, unsigned char code )
{
    int i;
    if ( p->iBytePosition >= STREAM_BUF_SIZE - 4 && p->iBytePosition > 0 )
    {
        i = fwrite( p->buf, 1, p->iBytePosition, p->f );
        if ( i != p->iBytePosition )
        {
            printf( "\nWrite file error" );
            exit( -1 );
        }
        p->iBytePosition = 0;
        p->iBitOffset    = 0;
    }
    p->buf[p->iBytePosition]     = 0;
    p->buf[p->iBytePosition + 1] = 0;
    p->buf[p->iBytePosition + 2] = 1;
    p->buf[p->iBytePosition + 3] = code;
    p->iBytePosition += 4;
    p->iBitsCount    += 32;
    p->uPreBytes      = ( uint32_t )code + 256;

    return 0;
}


/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
int write_video_edit_code()
{
    bitstream_t *bitstream;
    byte VideoEditCode[32];
    int bitscount = 0;

    if ( ( bitstream = calloc( 1, sizeof( bitstream_t ) ) ) == NULL )
        no_mem_exit( "Seuqence Header: bitstream" );

    bitstream->stream_buffer = VideoEditCode;
    bitstream->bits_to_go    = 8;

    bitscount = u_v( 32, "video_edit_code", 0x1B7, bitstream );

    write_start_code( pORABS, 0xb7 );

    free( bitstream );

    return bitscount;
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static int write_seq_header()
{
    bitstream_t *bitstream;
    byte seq_header[MAX_HEADER_SIZE];
    int bitscount = 0;
    int stuffbits;
    int i, j, k;
    if ( ( bitstream = calloc( 1, sizeof( bitstream_t ) ) ) == NULL )
        no_mem_exit( "Seuqence Header: bitstream" );

    bitstream->stream_buffer        = seq_header;
    bitstream->bits_to_go          = 8;
    input->display_horizontal_size = img->width;
    input->display_vertical_size   = img->height;
    input->sample_precision        = 1;

    check_bbs_size( input->profile_id, input->level_id, &input->bbs_size );
    input->bbv_buf_size = input->bbs_size >> 14;

    input->aspect_ratio_infor = 1;
    input->bit_rate_lower = ( input->bit_rate / 400 ) & ( 0x3FFFF );
    input->bit_rate_upper = ( input->bit_rate / 400 ) >> 18;

    bitscount += u_v( 32, "seqence start code", 0x1b0, bitstream );
    bitscount += u_v( 8, "profile_id", input->profile_id, bitstream );
    bitscount += u_v( 8, "level_id", input->level_id, bitstream );
    if( input->profile_id == 0x20 )
        bitscount += u_v( 3, "numberBidirectionallyPredictedPictures", input->succe_b, bitstream );

    bitscount += u_v( 14, "picture width", ( img->width - img->auto_crop_right ), bitstream );
    bitscount += u_v( 14, "picture height", ( img->height - img->auto_crop_bottom ), bitstream );
    bitscount += u_v( 4, "frame rate code", input->frame_rate_code, bitstream );
    bitscount += u_v( 18, "bit rate lower", input->bit_rate_lower, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );
    bitscount += u_v( 12, "bit rate upper", input->bit_rate_upper, bitstream );
    bitscount += u_v( 2, "chroma foramt", input->chroma_format, bitstream );
    bitscount += u_v( 2, "sample precision", input->sample_precision, bitstream );
    bitscount += u_v( 4, "aspect ratio information", input->aspect_ratio_infor, bitstream );
    bitscount += u_v( 2, "marker bit", 1, bitstream );
    bitscount += u_v( 1,  "pictureApplicationDataEnable", 0, bitstream );

    bitscount += u_v( 5, "reserved bits", 0, bitstream );

    k = bitscount >> 3;
    j = bitscount % 8;

    stuffbits = 8 - ( bitscount % 8 );

    if ( stuffbits < 8 )
        bitscount += u_v( stuffbits, "stuff bits for byte align", 0, bitstream );

    write_start_code( pORABS, 0xb0 );

    for ( i = 4; i < k; i++ )
        write_n_bit( pORABS, seq_header[i], 8 );

    write_n_bit( pORABS, seq_header[k], j );
    write_align_stuff( pORABS );

    free( bitstream );

    return bitscount;
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static int write_seq_end()
{
    write_start_code( pORABS, 0xb1 );
    return 32;
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static int write_seq_display_ext()
{
    bitstream_t *bitstream;
    byte SequenceDisplayExtension[MAX_HEADER_SIZE];
    int bitscount = 0;
    int stuffbits;
    int i, j, k;

    if ( ( bitstream = calloc( 1, sizeof( bitstream_t ) ) ) == NULL )
        no_mem_exit( "Sequence Display Extension: bitstream" );
    input->video_format = 1;
    input->video_range = 1;
    input->display_horizontal_size = 1920;
    input->display_vertical_size = 1280;

    bitstream->stream_buffer = SequenceDisplayExtension;
    bitstream->bits_to_go = 8;

    bitscount += u_v( 32, "sequence display extension start code", 0x1b5, bitstream );
    bitscount += u_v( 4, "extension id", 2, bitstream );
    bitscount += u_v( 3, "video format", input->video_format, bitstream );
    bitscount += u_v( 1, "video range", input->video_range, bitstream );
    bitscount += u_v( 1, "color description", input->color_description, bitstream );

    if ( input->color_description )
    {
        bitscount += u_v( 8, "color primaries", input->color_primaries, bitstream );
        bitscount += u_v( 8, "matrix coefficients", input->matrix_coeff, bitstream );
    }

    bitscount += u_v( 14, "display horizontal size", input->display_horizontal_size, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );
    bitscount += u_v( 14, "display vertical size", input->display_vertical_size, bitstream );
    bitscount += u_v( 2, "reserved bits", 0, bitstream );

    k = bitscount >> 3;
    j = bitscount % 8;

    stuffbits = 8 - ( bitscount % 8 );

    if ( stuffbits < 8 )
    {
        bitscount += u_v( stuffbits, "stuff bits for byte align", 0, bitstream );
    }

    write_start_code( pORABS, 0xb5 );
    for ( i = 4; i < k; i++ )
        write_n_bit( pORABS, SequenceDisplayExtension[i], 8 );
    write_n_bit( pORABS, SequenceDisplayExtension[k], j );
    write_align_stuff( pORABS );

    free( bitstream );

    return bitscount;
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static int write_copyright_ext()
{
    bitstream_t *bitstream;
    byte CopyrightExtension[MAX_HEADER_SIZE];
    int bitscount = 0;
    int stuffbits;
    int i, j, k;

    if ( ( bitstream = calloc( 1, sizeof( bitstream_t ) ) ) == NULL )
        no_mem_exit( "Copyright Extension: bitstream" );

    bitstream->stream_buffer = CopyrightExtension;
    bitstream->bits_to_go = 8;

    bitscount += u_v( 32, "copyright extension start code", 0x1b5, bitstream );
    bitscount += u_v( 4, "extension id", 4, bitstream );
    bitscount += u_v( 1, "copyright flag", cp->copyright_flag, bitstream );
    bitscount += u_v( 8, "copyright id", cp->copyright_id, bitstream );
    bitscount += u_v( 1, "original or copy", cp->original_or_copy, bitstream );

    bitscount += u_v( 7, "reserved_bits", 0, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );

    bitscount += u_v( 20, "copyright number 1", cp->copyright_number, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );
    bitscount += u_v( 22, "copyright number 2", cp->copyright_number, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );
    bitscount += u_v( 22, "copyright number 3", cp->copyright_number, bitstream );

    k = bitscount >> 3;
    j = bitscount % 8;

    stuffbits = 8 - ( bitscount % 8 );

    if ( stuffbits < 8 )
    {
        bitscount += u_v( stuffbits, "stuff bits for byte align", 0, bitstream );
    }

    write_start_code( pORABS, 0xb5 );
    for ( i = 4; i < k; i++ )
        write_n_bit( pORABS, CopyrightExtension[i], 8 );
    write_n_bit( pORABS, CopyrightExtension[k], j );
    write_align_stuff( pORABS );

    free( bitstream );

    return bitscount;
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static int write_camera_para_ext()
{
    bitstream_t *bitstream;
    byte CameraParametersExtension[MAX_HEADER_SIZE];
    int bitscount = 0;
    int stuffbits;
    int i, j, k;

    if ( ( bitstream = calloc( 1, sizeof( bitstream_t ) ) ) == NULL )
        no_mem_exit( "Camera Parameters Extension: bitstream" );

    bitstream->stream_buffer = CameraParametersExtension;
    bitstream->bits_to_go = 8;

    bitscount += u_v( 32, "camera parameters extension start code", 0x1b5, bitstream );
    bitscount += u_v( 4, "extension id", 11, bitstream );
    bitscount += u_v( 1, "reserved_bits", 0, bitstream );
    bitscount += u_v( 7, "camera id", camera->camera_id, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );

    bitscount += u_v( 22, "height_of_image_device", camera->height_of_image_device, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );

    bitscount += u_v( 22, "focal_length", camera->focal_length, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );

    bitscount += u_v( 22, "f_number", camera->f_number, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );

    bitscount += u_v( 22, "vertical_angle_of_view", camera->vertical_angle_of_view, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );

    bitscount += u_v( 16, "camera_position_x_upper", camera->camera_direction_x, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );
    bitscount += u_v( 16, "camera_position_x_lower", camera->camera_direction_x, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );

    bitscount += u_v( 16, "camera_position_y_upper", camera->camera_direction_y, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );

    bitscount += u_v( 16, "camera_position_y_lower", camera->camera_direction_y, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );

    bitscount += u_v( 16, "camera_position_z_upper", camera->camera_direction_z, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );
    bitscount += u_v( 16, "camera_position_z_lower", camera->camera_direction_z, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );

    bitscount += u_v( 22, "camera_direction_x", camera->camera_direction_x, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );

    bitscount += u_v( 22, "camera_direction_y", camera->camera_direction_y, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );

    bitscount += u_v( 22, "camera_direction_z", camera->camera_direction_z, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );

    bitscount += u_v( 22, "image_plane_vertical_x", camera->image_plane_vertical_x, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );

    bitscount += u_v( 22, "image_plane_vertical_y", camera->image_plane_vertical_y, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );

    bitscount += u_v( 22, "image_plane_vertical_z", camera->image_plane_vertical_z, bitstream );
    bitscount += u_v( 1, "marker bit", 1, bitstream );

    bitscount += u_v( 32, "reserved_bits", 0, bitstream );

    k = bitscount >> 3;
    j = bitscount % 8;

    stuffbits = 8 - ( bitscount % 8 );

    if ( stuffbits < 8 )
    {
        bitscount += u_v( stuffbits, "stuff bits for byte align", 0, bitstream );
    }

    write_start_code( pORABS, 0xb5 );
    for ( i = 4; i < k; i++ )
        write_n_bit( pORABS, CameraParametersExtension[i], 8 );
    write_n_bit( pORABS, CameraParametersExtension[k], j );
    write_align_stuff( pORABS );

    free( bitstream );

    return bitscount;
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static int write_user_data( char *userdata )
{
    bitstream_t *bitstream;
    byte UserData[MAX_HEADER_SIZE];
    int bitscount = 0;

    if ( ( bitstream = calloc( 1, sizeof( bitstream_t ) ) ) == NULL )
        no_mem_exit( "User data: bitstream" );
    bitstream->stream_buffer = UserData;
    bitstream->bits_to_go = 8;

    bitscount += u_v( 32, "user data start code", 0x1b2, bitstream );
    write_start_code( pORABS, 0xb2 );
    while ( *userdata )
    {
        write_n_bit( pORABS, *userdata, 8 );
        bitscount += u_v( 8, "user data", *userdata++, bitstream );
    }
    write_align_stuff( pORABS );
    free( bitstream );

    return bitscount;
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void error( char *text, int code )
{
    fprintf( stderr, "%s\n", text );
    exit( code );
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
int start_sequence()
{
    int len = 0;
    char id_string[255] = "royal free test stream";
    if ( img->number == 0 )
        open_output_stream( pORABS, input->out_file );
    len  = write_seq_header();
    len += write_seq_display_ext();
    len += write_copyright_ext();
    len += write_camera_para_ext();
    if ( strlen( id_string ) > 1 )
        len += write_user_data( id_string );
    return len;
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
int terminate_sequence()
{
    int len;
    len = write_seq_end();
    if ( img->encode_end_flag == 1 )
        close_output_stream( pORABS );
    return len;
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void write_bs_to_file()
{
    int n, i;
    n = curr_stream->byte_pos;
    for ( i = 0; i < n; i++ )
    {
        if ( curr_stream->stream_buffer[i] == 0 && curr_stream->stream_buffer[i + 1] == 0 && curr_stream->stream_buffer[i + 2] == 1 )
        {
            write_start_code( pORABS, curr_stream->stream_buffer[i + 3] );
            i = i + 4;
        }

        write_n_bit( pORABS, curr_stream->stream_buffer[i], 8 );
    }
    stat->bit_ctr += 8 * n;
    stat->bit_ctr += stat->bit_use_header[3];
    stat->bit_use_header[3] = 0;
}

